﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;

namespace Zebra.DataAccess
{
    public class UsersRepository
    {
        private ZebraDataContext _dc;

        public UsersRepository(string cs)
        {
            _dc = new ZebraDataContext(cs);
        }

        public Boolean IsDirty()
        {
            return (
                    (_dc.GetChangeSet().Updates.Count > 0) ||
                    (_dc.GetChangeSet().Deletes.Count > 0) ||
                    (_dc.GetChangeSet().Inserts.Count > 0)
                );
        }

        public void Insert(User user)
        {
            _dc.Users.InsertOnSubmit(user);
            _dc.SubmitChanges();
        }

        public void Save()
        {
            if (IsDirty())
                _dc.SubmitChanges();
        }

        public void Delete(User user)
        {
            _dc.Staffs.DeleteOnSubmit(user.Staffs[0]);
            _dc.Users.DeleteOnSubmit(user);
            _dc.SubmitChanges();
        }

        public void Refresh(User user)
        {
            _dc.Refresh(RefreshMode.OverwriteCurrentValues, user);
        }

        public List<User> GetAllUsers()
        {
            return (from u in _dc.Users select u).ToList();
        }

        public User GetUserByName(string name)
        {
            return (from u in _dc.Users
                    where u.Name.StartsWith(name)
                    select u).SingleOrDefault();
        }
    }
}
